var _util = require('util/util.js');
require('./index.css');
require('page/common/header/index.js');

var _account_service = require('service/account-service.js');

var userLogin ={
    init : function(){
        $('#loginMsg').hide();
        this.bindEvents();
        return this;
    },
    bindEvents : function(){
        var _this = this;
        $('#submit').click(
            function(){
                _this.submit();
            }
        );
    },
    submit : function(){
        var formData = {
            username : $.trim($('#username').val()),
            password : $.trim($('#password').val())
        };
        var validationResult = this.formValidation(formData);
        console.log(validationResult);
        if(validationResult.status){
            //向服务器发送登录请求
            _account_service.login(
                formData , 
                function(res){
                    window.location.href = _util.getURLParam('redirect')||'./catalog-main.html';
                    // _util.getURLParam('redirect');
                },
                function(errMsg){
                    $('#loginMsg').show().text(errMsg);
                } 
            );
        }else{
            $('#loginMsg').show().text(validationResult.msg);
        }

    },
    formValidation : function(formData){
        var result = {
            status : false,
            msg    : ''
        };
        //用户名和密码都没有
        if((!_util.validateField('require',formData.username))&&(!_util.validateField('require',formData.password))){
            result.msg = '用户名和密码不能为空';
            return result;
        }
        //有用户名没密码
        if((!_util.validateField('require',formData.password))&&(_util.validateField('require',formData.username))){
            result.msg = '密码不能为空';
            return result;
        }
        //有密码没用户名
        if((!_util.validateField('require',formData.username))&&(_util.validateField('require',formData.password))){
            result.msg = '用户名不能为空';
            return result;
        }

        
        //校验通过
        result.status = true;
        result.msg = '校验通过';
        return result;
    }
};

module.exports = userLogin.init();